const bookService = require('./../services/books.service');
const fs = require('fs');
const path = require('path');
const uuidV4 = require('uuid/v4');

module.exports = {
    /**
     * 二手书添加
     */
    async addBook(ctx) {
        let result = {
            result: false,
            message: '',
        };
        let session = ctx.session;
        if (session.isLogin) {
            let formData = ctx.request.body;
            let pictures = [];
            if (ctx.request.files.picture) {
                pictures = [].concat(ctx.request.files.picture);
            }
            // console.log(ctx.request.files);
            let folderName = '';
            if (pictures && pictures.length > 0) {
                folderName = 'bp' + `${Date.now().toString()}`;
                // 创建文件夹
                fs.mkdirSync(path.join(__dirname, '../public/books/', folderName));
                for (let picture of pictures) {
                    // 创建可读流
                    const reader = fs.createReadStream(picture.path);
                    const ext = picture.name.split('.').pop();
                    let filePath = path.join(__dirname, '../public/books/') + `${folderName}/${uuidV4()}.${ext}`;
                    const upStream = fs.createWriteStream(filePath);
                    reader.pipe(upStream);
                }
            }
            // 写入数据库
            let res = await bookService.addBook({
                user_id: session.user_id,
                picture_directory: folderName,
                ...formData
            });
            if (res && res.affectedRows) {
                result.message = '添加成功';
                result.result = true;
            } else {
                result.message = '添加失败';
            };
        } else {
            result.message = '请先登录';
        }
        ctx.body = result;
    },

    /**
     * 二手书信息获取
     * 
     */
    async getBookInfo(ctx) {
        let result = {
            result: false,
            message: ''
        };
        let book_id = ctx.query.book_id;
        let res = await bookService.getInfoById({
            book_id
        });
        if (res) {
            let pictures = [];
            if (res.picture_directory) {
                let folderPath = path.join(__dirname, '../public/books/', res.picture_directory)
                pictures = bookService.readDir(folderPath, res.picture_directory);
            }
            result.result = true;
            result.user_id = res.user_id;
            result.name = res.name;
            result.tag = res.tag;
            result.price = res.price;
            result.description = res.description;
            result.picture = pictures;
            result.position = res.position;
            result.state = res.state;
        } else {
            result.message = '书籍ID不存在';
        }
        ctx.body = result;
    },
    /**
     * 二手书信息修改
     */
    async modifyBookInfo(ctx) {
        let result = {
            result: false,
            message: ''
        };
        let session = ctx.session;
        if (session.isLogin) {
            let formData = ctx.request.body;
            let pictures = [];
            if (ctx.request.files.picture) {
                pictures = [].concat(ctx.request.files.picture);
            }
            let user_id = session.user_id;
            let book_id = formData.book_id;
            // 查看是否已经有上传文件
            // let res_pic = await bookService.getPic({book_id});

            // 处理上传文件
            let folderName = '';
            if (pictures && pictures.length > 0) {
                folderName = 'bp' + `${Date.now().toString()}`;
                fs.mkdirSync(path.join(__dirname, '../public/books/', folderName));
                for (let picture of pictures) {
                    // 创建可读流
                    const reader = fs.createReadStream(picture.path);
                    const ext = picture.name.split('.').pop();
                    let filePath = path.join(__dirname, '../public/books/') + `${folderName}/${uuidV4()}.${ext}`;
                    const upStream = fs.createWriteStream(filePath);
                    reader.pipe(upStream);
                }
            }
            let res = await bookService.modifyBookInfo({ book_id }, {...formData, user_id }, folderName);
            if (res && res.changedRows) {
                result.result = true;
                result.message = '修改成功';
            } else {
                result.message = '修改失败';
            }
        } else {
            result.message = '请先登录';
        }
        ctx.body = result;
    },
    /**
     * 添加二手书评论
     */
    async addEvaluate(ctx) {
        let result = {
            result: false,
            message: ''
        };
        let formData = ctx.request.body;
        let session = ctx.session;
        if (session.isLogin) {
            let user_id = session.user_id;
            let book_id = formData.book_id;
            let description = formData.description;
            let res = await bookService.addEvaluate({
                user_id,
                book_id,
                description
            });
            if (res && res.affectedRows) {
                result.result = true;
                result.message = '评论成功';
            }
        } else {
            result.message = '请先登录';
        }
        ctx.body = result;
    },
    /**
     * 查看二手书评论
     */
    async getEvaluate(ctx) {
        let result = {
            result: false,
            message: '',
            detail: []
        };
        let book_id = ctx.query.book_id;
        let res = await bookService.getEvaluate({ book_id });
        if (res.length > 0) {
            result.result = true;
            result.detail = res;
        }
        ctx.body = result;
    },
    /**
     * 二手书搜索
     */
    async searchBooks(ctx) {
        let result = {
            result: false,
            message: ''
        };
        let name = ctx.query.name;
        let tag = ctx.query.tag;
        let position = ctx.query.position;
        let price = ctx.query.price || false;
        let credit = ctx.query.credit || false;

        let res = await bookService.searchBooks({
            name,
            tag,
            position,
            price,
            credit
        });
        if (res.length > 0) {
            let ids = [];
            for (let item of res) {
                ids.push(item.book_id);
            }
            result.result = true;
            result.book_lists = ids;
        } else {
            result.message = '暂无搜索结果';
        }
        ctx.body = result;
    },
    /**
     * 今日推荐
     */
    async recommend(ctx) {
        let result = {
            result: false,
            message: ''
        };
        let res = await bookService.recommend();
        if (res.length > 0) {
            let ids = [];
            for (let item of res) {
                ids.push(item.book_id);
            }
            result.book_lists = ids;
            result.result = true;
        } else {
            result.message = '暂无推荐';
        }
        ctx.body = result;
    }
}